package com.wandousoushu.jiusen.ui.login;

import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.wandousoushu.jiusen.R;
import com.wandousoushu.jiusen.bean.CodeBean;
import com.wandousoushu.jiusen.util.CodeUtils;
import com.wandousoushu.jiusen.util.GsonUtils;
import com.wandousoushu.jiusen.util.ValidatePhoneUtil;
import com.wandousoushu.jiusen.web.http.MainHttpUtils;

import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class RetrievePasswordActivity extends AppCompatActivity {

    private EditText phoneEditText;
    private EditText codeEditText;
    private EditText passwordEditText;
    private EditText confirmPwdEditText;
    private TextView retrievePwdButton;
    private ImageView codeImageView;
    private String phoneNum;
    private String pwd;
    private String code;
    private String confirmPwd;
    private String serverCode;
    private String serverCodeUrl;
    private boolean isFirstCode=false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_retrieve_password);
        InitView();
    }

    private void InitView() {
        phoneEditText = findViewById(R.id.retrieve_edit_phone);
        codeEditText = findViewById(R.id.retrieve_edit_code);
        passwordEditText = findViewById(R.id.retrieve_edit_pwd);
        confirmPwdEditText = findViewById(R.id.retrieve_edit_confirm_pwd);
        retrievePwdButton = findViewById(R.id.btn_retrieve);
        codeImageView = findViewById(R.id.retrieve_iv_code);
        TextWatcher textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                phoneNum = phoneEditText.getText().toString();
                code = codeEditText.getText().toString();
                pwd = passwordEditText.getText().toString();
                confirmPwd = confirmPwdEditText.getText().toString();
                retrievePwdButton.setEnabled(!TextUtils.isEmpty(phoneNum) && !TextUtils.isEmpty(code) && !TextUtils.isEmpty(confirmPwd) && !TextUtils.isEmpty(pwd));
            }

            @Override
            public void afterTextChanged(Editable s) {
                if(!isFirstCode&&!TextUtils.isEmpty(phoneNum) && ValidatePhoneUtil.validateMobileNumber(phoneNum)){
                    isFirstCode=true;
                    HttpGetCode();
                }
            }
        };
        phoneEditText.addTextChangedListener(textWatcher);
        codeEditText.addTextChangedListener(textWatcher);
        passwordEditText.addTextChangedListener(textWatcher);
        confirmPwdEditText.addTextChangedListener(textWatcher);
        codeImageView.setVisibility(View.INVISIBLE);
        codeImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                HttpGetCode();
            }
        });

        retrievePwdButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Retrieve();
            }
        });
    }

    private void Retrieve() {
        if (TextUtils.isEmpty(phoneNum)) {
            phoneEditText.setError(getResources().getString(R.string.login_input_phone));
            phoneEditText.requestFocus();
            return;
        }
        if (!ValidatePhoneUtil.validateMobileNumber(phoneNum)) {
            phoneEditText.setError(getResources().getString(R.string.login_phone_error));
            phoneEditText.requestFocus();
            return;
        }
        if (TextUtils.isEmpty(pwd)) {
            passwordEditText.setError(getResources().getString(R.string.login_input_pwd));
            passwordEditText.requestFocus();
            return;
        }
        if (pwd.length() < 6 || pwd.length() > 16) {
            passwordEditText.setError(getResources().getString(R.string.invalid_password));
            passwordEditText.requestFocus();
            return;
        }
        if (TextUtils.isEmpty(confirmPwd)) {
            confirmPwdEditText.setError(getResources().getString(R.string.register_pwd_comfirm_null));
            confirmPwdEditText.requestFocus();
            return;
        }
        if (!pwd.equals(confirmPwd)) {
            confirmPwdEditText.setError(getResources().getString(R.string.register_pwd_confirm_error));
            confirmPwdEditText.requestFocus();
            return;
        }
        if (TextUtils.isEmpty(code)) {
            codeEditText.setError(getResources().getString(R.string.register_input_code));
            codeEditText.requestFocus();
            return;
        }
        if(!code.equals(serverCode)){
            codeEditText.setError(getResources().getString(R.string.register_code_error));
            codeEditText.requestFocus();
            return;
        }
        HttpRetrieve();
    }

    private void HttpRetrieve() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String  returnData = MainHttpUtils.getInstance().Retrieve(phoneNum, pwd, code);
                    if (returnData == null) {
                        mHandle.sendEmptyMessage(4);
                        return;
                    }
                    JSONObject jsonObject=new JSONObject(returnData);
                    if(jsonObject!=null&&jsonObject.getInt("code")==1){
                        mHandle.sendEmptyMessage(3);
                    }else {
                        Message msg = Message.obtain();
                        msg.obj = jsonObject.getString("msg");
                        msg.what = 5;
                        mHandle.sendMessage(msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void HttpGetCode() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String returnData= MainHttpUtils.getInstance().Getcode(phoneNum);
                    if(returnData==null){
                        mHandle.sendEmptyMessage(0);
                        return;
                    }
                    JSONObject jsonObject=new JSONObject(returnData);
                    if(jsonObject!=null&&jsonObject.getInt("code")==1){
                        CodeBean codeBean= GsonUtils.parseJObject(jsonObject.getString("data"),CodeBean.class);
                        serverCode=codeBean.getCode().toLowerCase();
                        serverCodeUrl=codeBean.getImg_url();
                        mHandle.sendEmptyMessage(1);
                    }else {
                        mHandle.sendEmptyMessage(0);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //设置网络图片
    public void setImageURL(final String path) {
        //开启一个线程用于联网
        new Thread() {
            @Override
            public void run() {
                try {
                    //把传过来的路径转成URL
                    URL url = new URL(path);
                    //获取连接
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    //使用GET方法访问网络
                    connection.setRequestMethod("GET");
                    //超时时间为10秒
                    connection.setConnectTimeout(10000);
                    //获取返回码
                    int code = connection.getResponseCode();
                    if (code == 200) {
                        InputStream inputStream = connection.getInputStream();
                        //使用工厂把网络的输入流生产Bitmap
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        //利用Message把图片发给Handler
                        Message msg = Message.obtain();
                        msg.obj = bitmap;
                        msg.what = 2;
                        mHandle.sendMessage(msg);
                        inputStream.close();
                    }else {
                        //服务启发生错误
                        mHandle.sendEmptyMessage(0);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    //网络连接错误
                    mHandle.sendEmptyMessage(0);
                }
            }
        }.start();
    }

    private Handler mHandle=new Handler(){
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0:
                    Toast.makeText(getApplicationContext(), getResources().getString(R.string.register_code_http_error), Toast.LENGTH_SHORT).show();
                    break;
                case 1:
                    //codeImageView.setImageBitmap(CodeUtils.getInstance().createBitmap(serverCode));
                    setImageURL(serverCodeUrl);
                    break;
                case 2:
                    codeImageView.setImageBitmap((Bitmap) msg.obj);
                    codeImageView.setVisibility(View.VISIBLE);
                    break;
                case 3:
                    Toast.makeText(getApplicationContext(), getResources().getString(R.string.retrieve_retrieve_http_success), Toast.LENGTH_SHORT).show();
                    finish();
                    break;
                case 4:
                    Toast.makeText(getApplicationContext(), getResources().getString(R.string.retrieve_retrieve_http_fail), Toast.LENGTH_SHORT).show();
                    break;
                case 5:
                    Toast.makeText(getApplicationContext(), msg.obj.toString(), Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };
}